#Author: Mike Schladt - 2014
#Utility Script to parse mongodb for errors
#RUN WITH -d to REMOVE ERRORS FROM THE MONGODB 

import json
import sys
from pymongo import MongoClient

connection_string = 'mongodb://localhost:27017/'

try:
    arg1 = sys.argv[1]
except:   
    arg1 = 'NONE'

#connect to the db
client = MongoClient(connection_string)
db = client.cuckoo
analysis = db.analysis

#retrive errors 

results = analysis.find( {'debug.errors' : { '$type' : 2 } } , { 'debug.errors' : 1 , 'target.file.md5' : 1 } ) 

for result in results :
    try:
       
        ID = result['_id']
        error = str(result['debug']['errors'])
        md5 = str(result['target']['file']['md5'])   
        print md5 + " : " + error 
        if arg1 == "-d" :
            analysis.remove( { "_id" : ID } )
            print " REMOVED"
        
        
    except Exception as e:
        print e

